<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="140px"
      v-loading="formLoading"
    >
      <el-form-item label="平台编号" prop="platformId">
        <el-input v-model="formData.platformId" placeholder="请输入平台编号" />
      </el-form-item>
      <el-form-item label="店铺编号" prop="storeId">
        <el-input v-model="formData.storeId" placeholder="请输入店铺编号" />
      </el-form-item>
      <el-form-item label="认证类型" prop="authType">
        <el-select v-model="formData.authType" placeholder="请选择认证类型">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CROSSBORDER_AUTH_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客户端ID" prop="clientId">
        <el-input v-model="formData.clientId" placeholder="请输入客户端ID" />
      </el-form-item>
      <el-form-item label="客户端密钥" prop="clientSecret">
        <el-input v-model="formData.clientSecret" placeholder="请输入客户端密钥" />
      </el-form-item>
      <el-form-item label="访问令牌" prop="accessToken">
        <el-input v-model="formData.accessToken" placeholder="请输入访问令牌" />
      </el-form-item>
      <el-form-item label="刷新令牌" prop="refreshToken">
        <el-input v-model="formData.refreshToken" placeholder="请输入刷新令牌" />
      </el-form-item>
      <el-form-item label="令牌类型" prop="tokenType">
        <el-select v-model="formData.tokenType" placeholder="请选择令牌类型">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.CROSSBORDER_TOKEN_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="授权范围" prop="scope">
        <el-input v-model="formData.scope" placeholder="请输入授权范围" />
      </el-form-item>
      <el-form-item label="令牌有效期（秒）" prop="expiresIn">
        <el-input v-model="formData.expiresIn" placeholder="请输入令牌有效期（秒）" />
      </el-form-item>
      <el-form-item label="令牌过期时间" prop="tokenExpireTime">
        <el-date-picker
          v-model="formData.tokenExpireTime"
          type="date"
          value-format="x"
          placeholder="选择令牌过期时间"
        />
      </el-form-item>
      <el-form-item label="API密钥" prop="apiKey">
        <el-input v-model="formData.apiKey" placeholder="请输入API密钥" />
      </el-form-item>
      <el-form-item label="API密钥" prop="apiSecret">
        <el-input v-model="formData.apiSecret" placeholder="请输入API密钥" />
      </el-form-item>
      <el-form-item label="额外参数JSON" prop="additionalParams">
        <el-input v-model="formData.additionalParams" placeholder="请输入额外参数JSON" />
      </el-form-item>
      <el-form-item label="授权状态" prop="authStatus">
        <el-select v-model="formData.authStatus" placeholder="请选择授权状态">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CROSSBORDER_AUTH_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="授权时间" prop="authTime">
        <el-date-picker
          v-model="formData.authTime"
          type="date"
          value-format="x"
          placeholder="选择授权时间"
        />
      </el-form-item>
      <el-form-item label="最后刷新时间" prop="lastRefreshTime">
        <el-date-picker
          v-model="formData.lastRefreshTime"
          type="date"
          value-format="x"
          placeholder="选择最后刷新时间"
        />
      </el-form-item>
      <el-form-item label="授权错误信息" prop="authErrorMsg">
        <el-input v-model="formData.authErrorMsg" placeholder="请输入授权错误信息" />
      </el-form-item>
      <el-form-item label="自动刷新" prop="autoRefresh">
        <el-select v-model="formData.autoRefresh" placeholder="请选择是否自动刷新">
          <el-option
            v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
            :key="String(dict.value)"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { DICT_TYPE, getIntDictOptions, getStrDictOptions, getBoolDictOptions } from '@/utils/dict'
import { PlatformAuthApi, PlatformAuthVO } from '@/api/crossborder/platformauth'

/** 跨境电商平台授权信息 表单 */
defineOptions({ name: 'PlatformAuthForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  platformId: undefined,
  storeId: undefined,
  authType: undefined,
  clientId: undefined,
  clientSecret: undefined,
  accessToken: undefined,
  refreshToken: undefined,
  tokenType: undefined,
  scope: undefined,
  expiresIn: undefined,
  tokenExpireTime: undefined,
  apiKey: undefined,
  apiSecret: undefined,
  additionalParams: undefined,
  authStatus: undefined,
  authTime: undefined,
  lastRefreshTime: undefined,
  authErrorMsg: undefined,
  autoRefresh: undefined,
})
const formRules = reactive({
  platformId: [{ required: true, message: '平台编号不能为空', trigger: 'blur' }],
  storeId: [{ required: true, message: '店铺编号不能为空', trigger: 'blur' }],
  authType: [{ required: true, message: '认证类型（1OAuth2 2API密钥 3JWT 4Basic Auth）不能为空', trigger: 'change' }],
  authStatus: [{ required: true, message: '授权状态（0未授权 1已授权 2授权过期 3授权失败）不能为空', trigger: 'blur' }],
  autoRefresh: [{ required: true, message: '是否自动刷新令牌不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await PlatformAuthApi.getPlatformAuth(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as PlatformAuthVO
    if (formType.value === 'create') {
      await PlatformAuthApi.createPlatformAuth(data)
      message.success(t('common.createSuccess'))
    } else {
      await PlatformAuthApi.updatePlatformAuth(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    platformId: undefined,
    storeId: undefined,
    authType: undefined,
    clientId: undefined,
    clientSecret: undefined,
    accessToken: undefined,
    refreshToken: undefined,
    tokenType: undefined,
    scope: undefined,
    expiresIn: undefined,
    tokenExpireTime: undefined,
    apiKey: undefined,
    apiSecret: undefined,
    additionalParams: undefined,
    authStatus: undefined,
    authTime: undefined,
    lastRefreshTime: undefined,
    authErrorMsg: undefined,
    autoRefresh: undefined,
  }
  formRef.value?.resetFields()
}
</script>